import React, { useRef, useEffect, useCallback, useState } from "react";
import useGesture from "@/utils/useGesture";
import "./index.scss";
import cx from "classnames";
import { conditionalExpression } from "@babel/types";


interface state {
  x: number;
  y: number;
}
export default (): JSX.Element => {
  const preCls = "drag-box";

  const [pos, setPos] = useState<state>({ x: 100, y: 100 });
  const boxRef = useRef<HTMLDivElement | null>(null);
  const disRef = useRef<state | null>({x:0,y:0})
  const [drag, setDraging] = useState<boolean>(false);

  const handleMouseDown = (e) => {
    // console.log("e", e.clientX,e.clientY);
    disRef.current.x = e.clientX - e.target.offsetLeft;
    disRef.current.y = e.clientY - e.target.offsetTop;
    setDraging(true);
    //  window.addEventListener('mousemove',handleMouseMove);
  };
  
   const handleMouseMove =({clientX,clientY})=>{
     
    // console.log('234');
    console.log('drag',drag);
     if(disRef.current&&drag){
      setPos({
        x:clientX - disRef.current.x,
        y:clientY  - disRef.current.y
      })
     }
    
   }
  const handleMouseUp = ()=>{
    console.log('mouseUpRemove');
    setDraging(false);
    // window.removeEventListener('mousemove',handleMouseMove);
  }
  useEffect(()=>{
    if(drag){
      window.addEventListener('mousemove', handleMouseMove);
      window.addEventListener('mouseup', handleMouseUp);
    }else{
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    }
  },[drag])

  const dragStyle: React.CSSProperties = {
    // transform: `translate3d(${pos.x}px,${pos.y}px,0)`,
    left:`${pos.x}px`,
    top:`${pos.y}px`,
    position:'fixed'
  };

  return (
    <div
      className={cx(preCls)}
      style={dragStyle}
      onMouseDown={handleMouseDown}
      // onMouseUp={handleMouseUp}
      ref={boxRef}
    >
      Test
    </div>
  );
};
